package com.linian.pushforcampus.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.linian.pushforcampus.domain.CampusActivity;
import com.linian.pushforcampus.domain.PushConfigure;
import com.linian.pushforcampus.domain.TotalPageNum;
import com.linian.pushforcampus.mapper.CampusActivityMapper;
import com.linian.pushforcampus.service.CampusActivityService;
import com.linian.pushforcampus.service.WechatAccessTokenService;
import com.linian.pushforcampus.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.linian.pushforcampus.util.HttpUtil.sendGetHearderRequest;

/**
 * packageName com.linian.pushforcampus.service.Impl
 *
 * @author Lennon
 * @className CampusActivityServiceImpl
 * @date 2023/11/10
 * @description TODO
 */
@Service
public class CampusActivityServiceImpl implements CampusActivityService {
    @Autowired
    private CampusActivityMapper campusActivityMapper;

    @Autowired
    private WechatAccessTokenService wechatAccessTokenService;


    @Autowired
    private PushConfigure pushConfigure;


    @Override
    public List<CampusActivity> queryAllActivity() {
        return campusActivityMapper.querryAllActivity();
    }

    @Override
    public List<CampusActivity> queryActivityByName(String name) {
        return campusActivityMapper.querryActivityByName(name);
    }

    @Override
    public int inserActivity(CampusActivity campusActivitie) {

        return campusActivityMapper.insertActivity(campusActivitie);
    }

    @Override
    public void delectActivityAll() {
        campusActivityMapper.delectActivityAll();
    }

    @Override
    public List<CampusActivity> parseActivitysApiJson(String campusActivityString) {

        JSONObject jsonObject = JSON.parseObject(campusActivityString);
        JSONObject subjectTypeVOList = jsonObject.getJSONObject("data").getJSONObject("subjectTypeVOList");
        JSONArray records = subjectTypeVOList.getJSONArray("records");
        List<CampusActivity> campusActivities = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            JSONObject record = records.getJSONObject(i);
            CampusActivity campusActivity = new CampusActivity();
            campusActivity.setPublishId(record.getString("publishId"));
            campusActivity.setActivityId(record.getString("activityId"));
            campusActivity.setSubjectType(record.getString("subjectType"));
            campusActivity.setActType(record.getString("actType"));
            campusActivity.setActTypeName(record.getString("actTypeName"));
            campusActivity.setActLevel(record.getString("actLevel"));
            campusActivity.setActLevelName(record.getString("actLevelName"));
            campusActivity.setSportType(record.getString("sportType"));
            campusActivity.setSportTypeName(record.getString("sportTypeName"));
            campusActivity.setDepartmentsName(record.getString("departmentsName"));
            campusActivity.setName(record.getString("name"));
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateStartTime = LocalDateTime.parse(record.getString("startTime").replace(".0", ""), formatter);
            campusActivity.setStartTime(dateStartTime);
            LocalDateTime dateEndTime = LocalDateTime.parse(record.getString("endTime").replace(".0", ""), formatter);
            campusActivity.setEndTime(dateEndTime);
            if (!StringUtils.isBlank(record.getString("activityApplyStartTime"))) {
                LocalDateTime dateApplyStartTime = LocalDateTime.parse(record.getString("activityApplyStartTime").replace(".0", ""), formatter);
                campusActivity.setActivityApplyStartTime(dateApplyStartTime);
            }
            if (!StringUtils.isBlank(record.getString("activityApplyStartTime"))) {
                LocalDateTime dateApplyEndTime = LocalDateTime.parse(record.getString("activityApplyEndTime").replace(".0", ""), formatter);
                campusActivity.setActivityApplyEndTime(dateApplyEndTime);
            }
            campusActivity.setActivityPlaceDetail(record.getString("activityPlaceDetail"));
            LocalDateTime now = LocalDateTime.now();
            campusActivity.setUpdateTime(now);
            //查询详细活动接口中的状态,并且封装进去
            campusActivity.setState(parseActivityDetailApiJson(getActivityDetailedJson(record.getString("publishId"))));
            campusActivities.add(campusActivity);


        }


        return campusActivities;
    }

    @Override
    public String parseActivityDetailApiJson(String activityDetailString) {
        JSONObject jsonObject = JSONObject.parseObject(activityDetailString);
        String applyTypeName = jsonObject.getJSONObject("data").getString("applyTypeName");
        return applyTypeName;
    }

    @Override
    public List<CampusActivity> judgmentEncapsulation(List<CampusActivity> campusActivitiesByDataBase, List<CampusActivity> campusActivitiesByJson) {
        List<CampusActivity> resultCampusActivity = new ArrayList<>();

        //如果数据不平衡直接记录下来,前后对比
        //说明是上架
        List<CampusActivity> notFoundList1 = campusActivitiesByJson.stream()
                .filter(activity -> campusActivitiesByDataBase.stream()
                        .noneMatch(dataBaseActivity -> dataBaseActivity.getActivityId().equals(activity.getActivityId())))
                .map(activity -> {
                    activity.setUpperandlowerStatus("上架");
                    return activity;
                })
                .collect(Collectors.toList());
        //说明是下架，下架不需要关注，用户报名了自己清楚就行
//        List<CampusActivity> notFoundList2 = campusActivitiesByDataBase.stream()
//                .filter(activity -> campusActivitiesByJson.stream()
//                        .noneMatch(campusActivity -> campusActivity.getActivityId().equals(activity.getActivityId())))
//                .map(activity -> {
//                    activity.setUpperandlowerStatus("下架");
//                    return activity;
//                })
//                .collect(Collectors.toList());
        //如果数据库中的数据单独请求,拿到的state不相同,也记录下来(暂时不需要了,因为多了报名开始时间和结束时间)
//        for (CampusActivity campusActivity : campusActivitiesByDataBase) {
//
//            //如果查不到数据，null会转成空字符串
//            String state = StringUtils.defaultIfEmpty(parseActivityDetailApiJson(getActivityDetailedJson(campusActivity.getPublishId())), "");
//
//            if (!state.equals(campusActivity.getState())) {
//                resultCampusActivity.add(campusActivity);
//            }
//
//        }
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //说明是开始报名了
        // 说明是开始报名了,通过当前时间喝刷新拉去的时间进行对比,正好是开始时间的1min内,则进行一次报名推送,有且只有一次的报名推送
        List<CampusActivity> filteredActivitiesByTime = campusActivitiesByJson.stream()
                .filter(activity -> activity.getActivityApplyStartTime() != null &&
                        ChronoUnit.MINUTES.between(activity.getActivityApplyStartTime(), now) <= 1 &&
                        ChronoUnit.MINUTES.between(activity.getActivityApplyStartTime(), now) >= 0)
                .peek(activity -> activity.setUpperandlowerStatus("开始报名"))
                .collect(Collectors.toList());
//
//        // 数据库测试
//        List<CampusActivity> test = campusActivitiesByDataBase.stream()
//                .filter(activity -> activity.getActivityApplyStartTime() != null &&
//                        ChronoUnit.MINUTES.between(activity.getActivityApplyStartTime(), now) <= 1 &&
//                        ChronoUnit.MINUTES.between(activity.getActivityApplyStartTime(), now) >= 0)
//                .peek(activity -> activity.setUpperandlowerStatus("开始报名"))
//                .collect(Collectors.toList());


        resultCampusActivity.addAll(notFoundList1);
        //下架忽略
        //resultCampusActivity.addAll(notFoundList2);
//        resultCampusActivity.addAll(test);
        resultCampusActivity.addAll(filteredActivitiesByTime);


        //取出name包含嘉善的，还有活动地点包含嘉善的推送活动，主表数据不做更改，只是更改了推送时候的数据,不包含的将会remove
        if (resultCampusActivity.size() > 0) {
            for (int i = 0; i < resultCampusActivity.size(); i++) {
                if (resultCampusActivity.get(i).getName().contains("嘉善") || resultCampusActivity.get(i).getActivityPlaceDetail().contains("嘉善")) {
                    resultCampusActivity.remove(i);
                    i--;

                }

            }
            //说明当前数据表数据改变。重置数据库表，重新进行插入操作
            delectActivityAll();
            //重新进行插入操作，同步数据
            for (CampusActivity campusActivity : campusActivitiesByJson) {


                inserActivity(campusActivity);
            }
        }

        return resultCampusActivity;
    }

    @Override
    public TotalPageNum pareApiJsonGetTotalPageNum(String campusActivityString) {


        try {
            JSONObject jsonObject = JSON.parseObject(campusActivityString);
            JSONObject subjectTypeVOList = jsonObject.getJSONObject("data").getJSONObject("subjectTypeVOList");
            int pages = subjectTypeVOList.getIntValue("pages");
            return new TotalPageNum(pages);
        } catch (Exception e) {
            //说明请求异常，token失效。封装空信息提醒更换token
            String accessToken = wechatAccessTokenService.getWechatAccessTokenById(1).getAccessToken();
            String urlToDevelopers = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject();
            JSONObject newsObject = new JSONObject();
            JSONArray articlesArray = new JSONArray();
            JSONObject articleObject = new JSONObject();
            articleObject.put("title", "TOKEN失效");
            articleObject.put("description", "尽快更换TOKEN");
            articleObject.put("picurl", "https://img1.baidu.com/it/u=525130350,248247963&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1700326800&t=6da0a8c078e62c795c055dc673688e24");
            articlesArray.add(articleObject);
            newsObject.put("articles", articlesArray);
            jsonObject.put("news", newsObject);
            jsonObject.put("msgtype", "news");
            jsonObject.put("touser", pushConfigure.getDEVELOPEROPENID());
            String jsonString = jsonObject.toString();

            try {
                HttpUtil.sendPostRequest(urlToDevelopers, jsonString);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }


            return new TotalPageNum(1);
        }


    }

    @Override
    public List<String> getActivityByUserXToken(String XToken) throws IOException {
        List<String> result = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        sb.append("?current=");
        sb.append("1");
        extracted(sb);
        String CampOut = HttpUtil.sendGetHearderRequest(pushConfigure.getCAMPUSACTIVITYSURLFORUSER() + sb, XToken);
        JSONObject jsonObject = JSONObject.parseObject(CampOut);
        result.add(CampOut);
        JSONObject data = jsonObject.getJSONObject("data");
        int pages = data.getIntValue("pages");
        for (int i = 2; i <= pages; i++) {
            StringBuilder sbIn = new StringBuilder();
            sbIn.append("?current=");
            sbIn.append(i);
            extracted(sbIn);
            String CampOutT = HttpUtil.sendGetHearderRequest(pushConfigure.getCAMPUSACTIVITYSURLFORUSER() + sbIn, XToken);
            result.add(CampOutT);
        }
        return result;
    }

    private static void extracted(StringBuilder sb) {
        sb.append("&timeStamp=");
        sb.append(System.currentTimeMillis());
        sb.append("&endPoint=app");
    }


    @Override
    public String getActivityJsonByToken(int pageNum) {
        //获取定时获取token，没10秒钟获取一次token=
        String url = pushConfigure.getCAMPUSACTIVITYSURL().replace("PAGE_NUM", String.valueOf(pageNum));
        String result = null;
        try {
            result = sendGetHearderRequest(url, pushConfigure.getCampusToken());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return result;


    }

    @Override
    public String getActivityDetailedJson(String publishId) {

        String url = pushConfigure.getCAMPUSACTIVITYURL().replace("PUBLISH_ID", publishId);
        String result = "";
        try {
            result = sendGetHearderRequest(url, pushConfigure.getCampusToken());
        } catch (IOException e) {
            //找不到不管,说明该接口或者改活动没有,不终止程序即可
            throw new RuntimeException(e);
        }
        return result;
    }


}
